<?php

namespace App\Admin\Http\Controllers\Web;

use App\Admin\Eloquent\Message;
use App\Admin\Eloquent\User;
use App\Admin\Eloquent\UserMessage;
use App\Admin\Http\Controllers\Controller;
use App\Admin\Http\Requests\MessagesRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Laracasts\Flash\Flash;
use Symfony\Component\HttpFoundation\Request;

class MessagesController extends Controller
{
    /**
     * 返回消息列表
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        //获取用户请求参数
        $query = $request->only('title');

        $messages = Message::paging_query($query);

        //追加分页条件
        if (!empty($query))
            $messages->appends($query);

        $links = $messages->render();

        return view('admin.web.messages.index', compact('messages', 'query', 'links'));
    }

    /**
     * 返回创建消息表单
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create()
    {
        $author = $this->currentUser()->username;

        $message_types = Message::get_message_types();

        $receiver_types = Message::get_receiver_types();

        return view('admin.web.messages.create', compact('author', 'message_types', 'receiver_types'));
    }

    /**
     * 保存一条消息记录
     *
     * @param MessagesRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(MessagesRequest $request)
    {
        //获取所有请求参数
        $args = $request->all();

        //指定接收人
        //开启事务
        DB::beginTransaction();
        try {
            //中间逻辑代码

            //保存消息
            $message = new Message($args);
            $message->save();

            //获取消息id
            $msg_id = $message->id;

            //保存消息接收关系
            $this->save_user_msg($msg_id, $args['receiver_type'], isset($args['receiver_ids']) ? $args['receiver_ids'] : []);

            DB::commit();

            Flash::success('保存一条消息成功');
            return $this->redirectAction('Web\MessagesController@index');
        } catch (\Exception $e) {
            //接收异常处理并回滚
            DB::rollBack();

            Flash::error('保存一条消息失败,请重试!');

            return $this->redirectAction('Web\MessagesController@index');
        }
    }

    public function edit($id)
    {
        $message = Message::findOrFail($id);

        $message_types = Message::get_message_types();

        $old_receivers = $this->get_receivers_by_message($message->id);

        $receiver_types = Message::get_receiver_types();


        return view('admin.web.messages.edit', compact('message_type', 'old_receivers', 'receiver_types', 'message_types', 'message'));
    }

    /**
     * 修改指定的消息
     *
     * @param MessagesRequest $request
     * @param int $id
     * @return \Exception
     */
    public function update(MessagesRequest $request, int $id)
    {
        $args = $request->all();


        //指定接收人
        //开启事务
        DB::beginTransaction();
        try {
            //中间逻辑代码

            //保存消息
            $message = Message::findOrFail($id)->update($args);

            //清除已有的消息关系记录
            UserMessage::where('message_id', $id)->delete();

            //保存消息接收人关系记录
            $this->save_user_msg($id, $args['receiver_type'], isset($args['receiver_ids']) ? $args['receiver_ids'] : []);

            DB::commit();
            Flash::success('更新一条消息成功');

            return $this->redirectAction('Web\MessagesController@index');
        } catch (\Exception $e) {
            return $e;
            //接收异常处理并回滚
            DB::rollBack();

            Flash::error('更新一条消息失败,请重试!');
            return $this->redirectAction('Web\MessagesController@index');
        }
    }

    /**
     * 删除一个消息记录
     *
     * @param int $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(int $id)
    {
        DB::beginTransaction();
        try {
            //找到指定消息
            Message::findOrFail($id)->delete();
            UserMessage::where('message_id', $id)->delete();

            //根据消息ID查询消息

            DB::commit();
            Flash::success('删除一条消息成功!');
            return $this->redirectAction('Web\MessagesController@index');
        } catch (\Exception $e) {
            //接收异常处理并回滚
            DB::rollBack();

            Flash::error('删除一条消息失败!');
            return $this->redirectAction('Web\MessagesController@index');
        }
    }

    /**
     * 根据id查看一条消息详情
     *
     * @param int $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function show(int $id)
    {
        $message = Message::findOrFail($id);

        $old_receivers = $this->get_receivers_by_message($message->id);

        return view('admin.web.messages.show', compact('message', 'old_receivers'));
    }

    /**
     * 删除一年以前的消息记录
     */
    public function clear_message_status()
    {
        DB::beginTransaction();
        try {

            $msg_ids = Message::select('id')->where('created_at', '<', '' . date('Y-m-d H:i:s', strtotime("-1 year")))->get();

            //根据消息id删除对应的消息关系记录
            foreach ($msg_ids as $msg_id) {
                UserMessage::where('message_id', $msg_id)->delete();
            }
            DB::commit();
            Flash::success('成功清除一年前的消息记录!');
            return $this->redirectAction('Web\MessagesController@index');

        } catch (\Exception $e) {
            //接收异常处理并回滚
            DB::rollBack();
            Flash::error('清除消息记录失败!');
            return $this->redirectAction('Web\MessagesController@index');
        }
    }

    /**
     * 保存用户消息记录
     */
    public function save_user_msg(int $msg_id, string $receiver_type, array $receiver_ids = [])
    {
        //TODO 保存用户消息记录  --根据业务需求持续增加--
        switch ($receiver_type) {
            case "select_users":
                $ids = implode(',', $receiver_ids);

                DB::select("insert INTO user_messages SELECT $msg_id,id,0   from users WHERE id IN ($ids)");
                break;
            case "all_users":
                ;
                DB::select("insert INTO user_messages SELECT $msg_id,id,0   from users");
                break;
        }
    }

    /**
     * 根据消息ID查询 该消息的接收人信息
     *
     * @param int $message_id
     * @return mixed
     */
    public function get_receivers_by_message(int $message_id)
    {
        //TODO 根据消息ID查询 该消息的接收人信息 --待完善--
        return $receiver_ids = User::select('users.username', 'b.user_id')
            ->leftJoin('user_messages as b', 'b.user_id', '=', 'users.id')
            ->where('b.message_id', $message_id)
            ->get();
    }

    /**
     * 根据条件模糊查询用户数组
     *
     * @param Request $request
     * @return array
     */
    public function query_receiver(Request $request)
    {
        //获取查询条件
        $query_str = $request->input('query_str');

        $users = User::leftJoin('user_info as a', 'a.user_id', '=', 'users.id')
            ->where('a.id_card', 'like', '%' . $query_str . '%')
            ->orWhere('a.name', 'like', '%' . $query_str . '%')
            ->get();

//        $users = Uer::all();
        $data = [];
        foreach ($users as $index => $user) {
            $data[$index] = ['id' => $user->id, 'text' => empty($user->userInfo->name) ? $user->username : $user->userInfo->name];
        }

        //返回用户数组
        return response()->json($data);
    }
}